import router from "./router";
import store from "./store";
import getPageTitle from "./utils/get-page-title";
import Cookies from 'js-cookie'
import {getSessAliveTs} from "./api/user";
import {ElMessage} from "element-plus";

let routeFlag = false
const whiteList = ['/goods/html']

router.beforeEach(async(to, ftom, next) => {
  document.title = getPageTitle(to.meta.title)
  await store.dispatch('user/getSessInfo')
  const islogin = store.getters.islogin
  const backurl = encodeURIComponent(window.location.href)
  const alivets = Cookies.get('sessalivets') ? Cookies.get('sessalivets') : 0

  const nowtime = Date.parse(new Date())/1000;

  if (islogin) {
    if (nowtime - alivets >= 180) {
      getSessAliveTs()
    }
    const isselectcorp = store.getters.isselectcorp
    if (isselectcorp) {
      if (routeFlag) {
        next()
      } else {
        const sysindex = store.getters.syslist.findIndex(d => d.code == 'VCLOUD_PROJECT')
        let projectRoutes = []
        if (sysindex != -1) {
          projectRoutes = await store.dispatch('project/getProjectRouteList')
        }
        await store.dispatch('user/contactSyslist', projectRoutes)
        const accessRoutes = await store.dispatch('permission/generateRoutes', ['admin'])
        await accessRoutes.forEach((route) => {
          if (route.meta && process.env.VUE_APP_BASE_URL == route.meta.jumpbaseurl) {
            router.addRoute(route)
          }
        })
        routeFlag = true
        if (!router.hasRoute(to.name)) {
          ElMessage({
            type: 'warning',
            message: '没有权限或页面找不到',
            duration: 2000,
            onClose: () => {
              window.location.href = process.env.VUE_APP_BASE_VCLOUD_URL + '/dashboard/index'
            }
          })
        } else {
          next({...to, replace: true})
        }
      }
    } else {
      // 未选择组织，跳转到选择组织页面
      window.location.href = process.env.VUE_APP_BASE_VCLOUD_URL + '/selectCorp?backurl=' + backurl
    }
  } else {
    // 判断路由是否在白名单中
    if (whiteList.indexOf(to.path) == -1) {
      // 不在白名单中跳转到登录页面
      window.location.href = process.env.VUE_APP_BASE_VCLOUD_URL + '/login?backurl=' + backurl
    } else {
      // 在白名单中可以直接下一步
      next()
    }
    // 未登录，跳转到登录页面
    // window.location.href = process.env.VUE_APP_BASE_VCLOUD_URL + '/login?backurl=' + backurl
  }
})
